package com.example.sse.controller;

import com.example.sse.service.ClusterCommunicationService;
import com.example.sse.service.DataGeneratorService;
import com.example.sse.service.SseConnectionManager;
import com.example.sse.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;

/**
 * SSE控制器
 * 提供SSE连接和消息推送接口
 */
@Slf4j
@RestController
@RequestMapping("/api/sse")
@RequiredArgsConstructor
public class SseController {

    private final SseConnectionManager sseConnectionManager;
    private final ClusterCommunicationService clusterCommunicationService;
    private final DataGeneratorService dataGeneratorService;

    /**
     * 建立SSE连接
     * @param clientId 客户端ID（可选）
     * @return SseEmitter
     */
    @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(@RequestParam(required = false) String clientId) {
        log.info("客户端请求建立SSE连接: {}", clientId != null ? clientId : "anonymous");
        return sseConnectionManager.createConnection(clientId);
    }

    /**
     * 获取连接状态
     * @return 连接状态信息
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getConnectionStatus() {
        Map<String, Object> status = MapUtils.of(
            "activeConnections", sseConnectionManager.getActiveConnectionCount(),
            "nodeId", sseConnectionManager.getNodeId(),
            "clusterInfo", clusterCommunicationService.getClusterNodeInfo(),
            "serverTime", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(status);
    }

    /**
     * 手动推送自定义消息
     * @param request 消息请求
     * @return 推送结果
     */
    @PostMapping("/push")
    public ResponseEntity<Map<String, Object>> pushMessage(@RequestBody PushMessageRequest request) {
        try {
            dataGeneratorService.generateCustomData(request.getType(), request.getContent());
            
            Map<String, Object> result = MapUtils.of(
                "success", true,
                "message", "消息推送成功",
                "type", request.getType(),
                "timestamp", System.currentTimeMillis()
            );
            
            log.info("手动推送消息成功: {}", request.getType());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("推送消息失败", e);
            Map<String, Object> result = MapUtils.of(
                "success", false,
                "message", "消息推送失败: " + e.getMessage(),
                "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取集群节点信息
     * @return 集群信息
     */
    @GetMapping("/cluster/info")
    public ResponseEntity<Map<String, Object>> getClusterInfo() {
        Map<String, Object> clusterInfo = MapUtils.of(
            "currentNode", MapUtils.of(
                "nodeId", sseConnectionManager.getNodeId(),
                "activeConnections", sseConnectionManager.getActiveConnectionCount()
            ),
            "clusterDescription", clusterCommunicationService.getClusterNodeInfo(),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(clusterInfo);
    }

    /**
     * 推送消息请求模型
     */
    public static class PushMessageRequest {
        private String type;
        private Object content;

        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        public Object getContent() { return content; }
        public void setContent(Object content) { this.content = content; }
    }
}